#include <iostream>
#include <unordered_set>

using namespace std;

static bool prime(int n) {
    if (n < 2)
        return false;
    if (n == 2)
        return true;
    if (n % 2 == 0)
        return false;
    for (int i = 3; i * i <= n; i += 2)
        if (n % i == 0)
            return false;
    return true;
}

static bool circular_prime(int num, const unordered_set<int>& primes) {
    auto circular = [](int a){
        if (a < 10)
            return a;
        int b = a % 10;
        int d = 1;
        while (d < a)
            d *= 10;
        return (a + b * d) / 10;
    };
    if (num < 10)
        return true;
    for (int n = circular(num); n != num; n = circular(n)) {
        // cout << num << ',' << n << endl;
        if (primes.find(n) == primes.end())
            return false;
    }
    return true;
}

int main() {
    unordered_set<int> primes;
    for (int i = 0; i < 1000000; i++) {
        if (prime(i)) {
            cout << i << endl;
            primes.insert(i);
        }
    }
    cout << "all ... \n";
    int count = 0;
    for (int i : primes) {
        if (circular_prime(i, primes)) {
            cout << i << endl;
            count++;
        }
    }
    cout << count << endl; // 55
}